
package com.zcp.wizard;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.widget.RemoteViews;

/**
 * 注意在onstart方法中不能做一些实质性动作，因为为了卸载安装（有安装widget）下自动重启服务。 在引导页面会调用启用服务。
 * 
 * @author Administrator
 */
public class WidgetStatusObserverService extends android.app.Service {

    private BatteryChangeReceiver batteryChange = null;

    private IntentFilter intentFilter = null;

    private Context context;

    private int[] batteryValues = new int[5];

    private static final int MSG_UPDATE_SYSTEM_WIDGET = 2;

    private RemoteViews rv = null;

    private boolean isScreenOn = true;

    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    @Override
    public void onCreate() {
        context = this;
        checkParam();
        rv = WidgetUtils.buildUpdate(this);
        registerReceiver(batteryChange, intentFilter);// 电池变化事件只能通过注册来监听
        handler.sendEmptyMessageDelayed(MSG_UPDATE_SYSTEM_WIDGET, 30000);
        // Log.i("tag1", "3333333333333333333333333333");
    }
  

    @Override
    public void onDestroy() {
        try {
            handler.removeMessages(MSG_UPDATE_SYSTEM_WIDGET);
            handler.removeCallbacks(task);
            handler.removeMessages(Constants.MSG_INIT_OK);
            if (batteryChange != null) {

                unregisterReceiver(batteryChange);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        batteryChange = null;
        intentFilter = null;
        handler = null;
        task = null;
        context = null;
        rv = null;
        batteryValues = null;

        super.onDestroy();
    }

    private void checkParam() {
        if (batteryChange == null) {
            batteryChange = new BatteryChangeReceiver();
        }
        if (intentFilter == null) {
            intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
            intentFilter.addAction(Intent.ACTION_SCREEN_ON);
            intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
            intentFilter.addAction(Constants.UPDATE_WIDGET);            
        }

    }

    private class BatteryChangeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }
            try {
                String action = intent.getAction();
                if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
                    dealWithWidgetBatteryChange(context, intent);
                } else if (Intent.ACTION_SCREEN_ON.equals(action)) {
                    isScreenOn = true;
                    // 解决在关闭屏幕以后 电池信息有变化不会同步更新问题
                    // Log.i("tag1", "ACTION_SCREEN_ON" + batteryValues[0] +
                    // "||" + batteryValues[1]
                    // + "||" + batteryValues[2] + "||" + batteryValues[3]);
                    if(batteryValues[1]>=0)
                    {
                    updateWidgetData(batteryValues[0], batteryValues[1], batteryValues[2],
                            batteryValues[3], batteryValues[4] == 1);
                    }
                    handler.sendEmptyMessageDelayed(MSG_UPDATE_SYSTEM_WIDGET, 30000);
                } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    isScreenOn = false;
                    handler.removeMessages(MSG_UPDATE_SYSTEM_WIDGET);
                }else if(Constants.UPDATE_WIDGET.equals(action))
                {
//                     Log.i("tag1", "UPDATE_WIDGET 2222222" + batteryValues[0] +
//                     "||" + batteryValues[1]
//                     + "||" + batteryValues[2] + "||" + batteryValues[3]+"||"+batteryValues[3]);
//                    int[] power=Util.getPowerInfo(context);
//                    if((power==null)||(power[1]<=0))
//                    {
//                        return;
//                    }
//                    batteryValues[0] = power[0];
//                    batteryValues[1] = power[1];
//                    batteryValues[2] = power[2];
//                    batteryValues[3] = power[3];
//                    batteryValues[4] = power[4];
//                    updateWidgetData(batteryValues[0], batteryValues[1], batteryValues[2],
//                            batteryValues[3], batteryValues[4] == 1);
                    if(batteryValues[1]>=0)
                    {
                    updateWidgetData(batteryValues[0], batteryValues[1], batteryValues[2],
                            batteryValues[3], batteryValues[4] == 1);
                    }
                }
                action = null;
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 处理收到(Intent.ACTION_BATTERY_CHANGED)广播更新widget方法。
     * 
     * @param context
     * @param intent
     */
    private void dealWithWidgetBatteryChange(Context context, Intent intent) {

        // RemoteViews rv = new RemoteViews(context.getPackageName(),
        // R.layout.widget);
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
        int temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
        // 电池状态
        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
                BatteryManager.BATTERY_STATUS_UNKNOWN);
        boolean present = intent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, false);

        batteryValues[0] = level;
        batteryValues[1] = scale;
        batteryValues[2] = temp;
        batteryValues[3] = status;
        batteryValues[4] = present ? 1 : 0;

        updateWidgetData(level, scale, temp, status, present);
    }

    public void updateWidgetData(int level, int scale, int temp, int status, boolean present) {
        // Log.i("tag1", "updateWidgetData"+ isScreenOn);
        if (!isScreenOn) {
            return;
        }
        // Log.i("tag1", "updateWidgetData begin");
        resetWidget(false);
        Util.undateWidgetBatteryStatus(status, rv, context, present);// 状态编出触发更新

        int power = level * 100 / scale;

        // //当不处于充电状态时候,当在MyCommonService 中做电池动画的时候需要加这个判断
        Util.updateImageViewBatteryPic(power, rv);// 根据电池电量在widget中设置相应的图片以显示电量

        rv.setTextViewText(R.id.txtBattery, power + "%");// 设置电池电量文字说明

        String tempafter = Util.tranTemp(temp, false);
        rv.setTextViewText(R.id.txtTemperature, tempafter); // 设置电池温度(d)
                                                            // 根据温度值变换数字颜色，如绿（≤35.9℃）-黄（36-60℃）-红（＞60℃）)
        float tempFloat = Float.valueOf(tempafter);

        Util.updateWidgetTempPic(tempFloat, rv);// 更新温度计图标
        Util.updateWidgetTempText(tempFloat, rv, context);// 更新温度计中指数

        Util.updateWidgetTip(status, power, tempFloat, rv, context, present);// 根据电量和温度更新提示语

        Util.updateWidget(context, rv);

        currentStatus = status;
        currentPower = power;
        currentTemp = tempFloat;
        // Log.i("tag", "have event " + currentPower + " currentTemp " +
        // currentTemp
        // + " currentStatus " + currentStatus);
        if (BatteryManager.BATTERY_STATUS_CHARGING == currentStatus) {
            currentStatusChanging++;
        } else {
            currentStatusChanging = -1;
        }
        startPowerMovie();
    }

    private int currentStatusChanging = -1;

    private int currentStatus = -1;

    private int currentPower = -1;

    private float currentTemp = -1;

    // 电量小于等于10%,温度大于等于60,电量充满,充电时候，就触发动画
    private void startPowerMovie() {
        // Log.i("tag", "begin movie currentPower " + currentPower +
        // " currentTemp " + currentTemp
        // + " currentStatus " + currentStatus);
        if ((currentPower <= Constants.POW_TIP10) || (currentTemp >= Constants.TEMPERATURE_TIP60)
                || (BatteryManager.BATTERY_STATUS_FULL == currentStatus)
                || (BatteryManager.BATTERY_STATUS_CHARGING == currentStatus)) {
            handler.post(task);
        }
    }

    /**
     * 停止动画和恢复
     */
    private void stopMovie() {

        handler.removeCallbacks(task);
        handler.removeMessages(Constants.MSG_INIT_OK);
        resetWidget(true);

    }

    private void resetWidget(boolean isNotice) {
        rv.setViewVisibility(R.id.wgBtryChickImage, View.VISIBLE);// 小鸡图片恢复正常
        for (int id : chickChangingIds) {
            rv.setViewVisibility(id, View.GONE);// 小鸡充电动画关闭
        }
        for (int id : chickChangedIds) {
            rv.setViewVisibility(id, View.GONE);// 小鸡电满动画关闭
        }
        for (int id : chickHotIds) {
            rv.setViewVisibility(id, View.GONE);// 小鸡温度高动画关闭
        }
        for (int id : chickLowPowerIds) {
            rv.setViewVisibility(id, View.GONE);// 小鸡低电量动画关闭
        }
        if (isNotice) {
            Util.updateWidget(this, rv);
        }
    }

    // wgBtryChickImage 正常时候
    // 要播放几遍动画就在下面原值数组加长
    private static int[] chickChangingIds = new int[] {
            R.id.wgBtryChg_1, R.id.wgBtryChg_2, R.id.wgBtryChg_1, R.id.wgBtryChg_2,
            R.id.wgBtryChg_1, R.id.wgBtryChg_2
    };// 充电时 3遍

    private static int[] chickChangedIds = new int[] {
            R.id.wgBtryFul_1, R.id.wgBtryFul_2, R.id.wgBtryFul_3, R.id.wgBtryFul_1,
            R.id.wgBtryFul_2, R.id.wgBtryFul_3
    };// 充满时 2遍

    private static int[] chickHotIds = new int[] {
            R.id.wgBtryHot_1, R.id.wgBtryHot_2, R.id.wgBtryHot_1, R.id.wgBtryHot_2,
            R.id.wgBtryHot_1, R.id.wgBtryHot_2
    };// 高温时 3遍

    private static int[] chickLowPowerIds = new int[] {
            R.id.wgBtryBad_1, R.id.wgBtryBad_2, R.id.wgBtryBad_3, R.id.wgBtryBad_1,
            R.id.wgBtryBad_2, R.id.wgBtryBad_3
    };// 低电量时 2遍

    private int currentPowIndex = 0;

    private int currentTempIndex = 0;

    private int currentStatusIndex = 0;

    private int currentStatusChangingIndex = 0;

    // 播放小鸡动画
    private void animationChick() {
        // 电量低于10开始播放动画
        if (currentPower <= Constants.POW_RED) {

            if (currentPowIndex > (chickLowPowerIds.length - 1)) {
                stopMovie();
                currentPowIndex = 0;
                currentPower = -1;
                // 最后设置显示电量低的图标
                rv.setViewVisibility(R.id.wgBtryChickImage, View.GONE);
                rv.setViewVisibility(R.id.wgBtryBad_1, View.VISIBLE);
                Util.updateWidget(this, rv);
                return;
            }

            rv.setViewVisibility(R.id.wgBtryChickImage, View.GONE);
            for (int id : chickLowPowerIds) {
                rv.setViewVisibility(id, View.GONE);
            }
            rv.setViewVisibility(chickLowPowerIds[currentPowIndex], View.VISIBLE);
            currentPowIndex++;
            Util.updateWidget(this, rv);
            handler.postDelayed(task, 500);

        } else if (currentTemp >= Constants.TEMPERATURE_TIP60) {

            if (currentTempIndex > (chickHotIds.length - 1)) {
                stopMovie();
                currentTempIndex = 0;
                currentTemp = -1;
                // 最后设置显示温度高的图标
                rv.setViewVisibility(R.id.wgBtryChickImage, View.GONE);
                rv.setViewVisibility(R.id.wgBtryHot_1, View.VISIBLE);
                Util.updateWidget(this, rv);
                return;
            }
            rv.setViewVisibility(R.id.wgBtryChickImage, View.GONE);
            for (int id : chickHotIds) {
                rv.setViewVisibility(id, View.GONE);
            }
            rv.setViewVisibility(chickHotIds[currentTempIndex], View.VISIBLE);
            currentTempIndex++;
            Util.updateWidget(this, rv);
            handler.postDelayed(task, 500);

        } else if (BatteryManager.BATTERY_STATUS_FULL == currentStatus) {
            if (currentStatusIndex > (chickChangedIds.length - 1)) {
                stopMovie();
                currentStatusIndex = 0;
                currentStatus = -1;
                // 最后设置显示电量满的图标
                rv.setViewVisibility(R.id.wgBtryChickImage, View.GONE);
                rv.setViewVisibility(R.id.wgBtryFul_1, View.VISIBLE);
                Util.updateWidget(this, rv);
                return;
            }
            rv.setViewVisibility(R.id.wgBtryChickImage, View.GONE);
            for (int id : chickChangedIds) {
                rv.setViewVisibility(id, View.GONE);
            }
            rv.setViewVisibility(chickChangedIds[currentStatusIndex], View.VISIBLE);
            currentStatusIndex++;
            Util.updateWidget(this, rv);
            handler.postDelayed(task, 500);
        } else if (BatteryManager.BATTERY_STATUS_CHARGING == currentStatus) {

            // 由于在充电状态会一直发，所以只是获取第一次，当状态改变的时候，currentStatusChanging会被置-1
            if (currentStatusChanging > -1) {
                return;
            }

            if (currentStatusChangingIndex > (chickChangingIds.length - 1)) {
                stopMovie();
                currentStatusChangingIndex = 0;
                currentStatus = -1;
                return;
            }
            rv.setViewVisibility(R.id.wgBtryChickImage, View.GONE);
            for (int id : chickChangingIds) {
                rv.setViewVisibility(id, View.GONE);
            }
            rv.setViewVisibility(chickChangingIds[currentStatusChangingIndex], View.VISIBLE);
            currentStatusChangingIndex++;
            Util.updateWidget(this, rv);
            handler.postDelayed(task, 500);
        }
    }

    Handler handler = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constants.MSG_INIT_OK:
                    animationChick();
                    break;
                case MSG_UPDATE_SYSTEM_WIDGET:
                    // Log.i("tag1", "MSG_UPDATE_SYSTEM_WIDGET ");
                    WidgetUtils.updateSystemStats(WidgetStatusObserverService.this, false);
                    handler.sendEmptyMessageDelayed(MSG_UPDATE_SYSTEM_WIDGET, 30000);
                    break;
            }
        };
    };

    Runnable task = new Runnable() {

        public void run() {
            handler.sendEmptyMessage(Constants.MSG_INIT_OK);
        }
    };

}
